/**

 @Name：layuiAdmin 公共业务
 @Author：贤心
 @Site：http://www.layui.com/admin/
 @License：LPPL
    
 */
 
layui.define(function(exports){
  var $ = layui.$
  ,layer = layui.layer
  ,laytpl = layui.laytpl
  ,setter = layui.setter
  ,view = layui.view
  ,admin = layui.admin
  
  //公共业务的逻辑处理可以写在此处，切换任何页面都会执行
  //……

    /**
     * name layui合并tbody中单元格的方法
     * @param tableId  表格的id属性
     * @param fieldName 要合并的列field值
     * @param leftOrRight 要合并的列fixed值,'left','right'
     * @desc 此方式适用于列冻结的单元格合并
     */
    admin.tableRowSpanOfFixedCol =function(tableId, fieldName, leftOrRight) {
        if (!tableId && !fieldName) {
            console.log('tableId, fieldName为必填项');
            return false;
        }

        // 获取页面中全部的表格元素
        var allTableNode = document.getElementsByClassName("layui-table-view");

        // 获取lay-id属性为tableId的表格元素的
        var targetTableNode = null;
        if (allTableNode.length > 0) {
            for (var index = 0, length = allTableNode.length; index < length; index++) {
                // 通过lay-id属性过滤表格元素
                var tableLayId = allTableNode[index].getAttribute("lay-id");
                if (tableLayId === tableId) {
                    targetTableNode = allTableNode[index];
                }
            }
        }
        if (!targetTableNode) {
            console.log('没有找到ID为：' + tableId + '的表格,请升级您的layui版本');
            return false;
        }
        // 左侧列为冻结的情况
        var tBodyNode = targetTableNode.getElementsByClassName("layui-table-body")[0];
        var tBodyNodeFixed = null;
        if (leftOrRight === 'right') {
            tBodyNodeFixed = targetTableNode.getElementsByClassName("layui-table-fixed-r")[0];
        } else {
            tBodyNodeFixed = targetTableNode.getElementsByClassName("layui-table-fixed-l")[0];
        }

        var tdNodesFixed = tBodyNodeFixed.getElementsByTagName("td");
        var tdNodes = tBodyNode.getElementsByTagName("td");
        var childFilterArrFixed = [];
        var childFilterArr = [];
        // 获取data-field属性为fieldName的td
        for (var i = 0; i < tdNodesFixed.length; i++) {
            if (tdNodesFixed[i].getAttribute("data-field") === fieldName) {
                childFilterArrFixed.push(tdNodesFixed[i]);
            }
        }
        for (var l = 0; l < tdNodes.length; l++) {
            if (tdNodes[l].getAttribute("data-field") === fieldName) {
                childFilterArr.push(tdNodes[l]);
            }
        }
        // 获取td的个数和种类
        var childFilterArrLength = childFilterArrFixed.length;
        var childFilterTextObj = {};
        for (var j = 0; j < childFilterArrLength; j++) {
            var childText = childFilterArrFixed[j].textContent;
            if (childFilterTextObj[childText] === undefined) {
                childFilterTextObj[childText] = 1;
            } else {
                var num = childFilterTextObj[childText];
                childFilterTextObj[childText] = num * 1 + 1;
            }
        }
        // 给获取到的td设置合并单元格属性
        for (var key in childFilterTextObj) {
            var tdNum = childFilterTextObj[key];
            var canRowSpan = true;
            var needChangeBackGroundNodesFixed = [];
            var needChangeBackGroundNodes = [];
            var addEventNode = null;
            for (var h = 0; h < childFilterArrLength; h++) {
                if (childFilterArrFixed[h].innerText === key) {
                    needChangeBackGroundNodesFixed.push(childFilterArrFixed[h]);
                    if (canRowSpan) {
                        childFilterArrFixed[h].setAttribute("rowspan", tdNum);
                        addEventNode = childFilterArrFixed[h];
                        canRowSpan = false;
                    } else {
                        childFilterArrFixed[h].style.display = "none";
                    }
                }
            }
            for (var m = 0; m < childFilterArrLength; m++) {
                if (childFilterArr[m].innerText === key) {
                    needChangeBackGroundNodes.push(childFilterArr[m]);
                }
            }

            // 以下为单元格鼠标悬浮样式修改(使用闭包)
            (function (addEventNode, needChangeBackGroundNodes, needChangeBackGroundNodesFixed) {
                addEventNode.onmouseover = function () {
                    for (var index = 0, length = needChangeBackGroundNodes.length; index < length; index++) {
                        needChangeBackGroundNodesFixed[index].parentNode.style.background = "#f2f2f2"; // 我这里的单元格鼠标滑过背景色为layui默认，你可以更改为你想要的颜色。
                        needChangeBackGroundNodes[index].parentNode.style.background = "#f2f2f2"; // 我这里的单元格鼠标滑过背景色为layui默认，你可以更改为你想要的颜色。
                    }
                };
                addEventNode.onmouseout = function () {
                    for (var index = 0, length = needChangeBackGroundNodes.length; index < length; index++) {
                        needChangeBackGroundNodesFixed[index].parentNode.style.background = "";
                        needChangeBackGroundNodes[index].parentNode.style.background = "";
                    }
                };
            })(addEventNode, needChangeBackGroundNodes, needChangeBackGroundNodesFixed);
        }
    }

    /**
     * name layui合并tbody中单元格的方法
     * @param tableId  表格的id属性
     * @param fieldName 要合并的列field值
     * @desc 此方式适用于没有列冻结的单元格合并
     */
    admin.tableRowSpanNoFixedCol=function (tableId, fieldName) {
        if (!tableId && !fieldName) {
            console.log('tableId, fieldName为必填项');
            return false;
        }
        // 获取页面中全部的表格元素
        var allTableNode = document.getElementsByClassName("layui-table-view");

        // 获取lay-id属性为tableId的表格元素的
        var targetTableNode = null;
        if (allTableNode.length > 0) {
            for (var index = 0, length = allTableNode.length; index < length; index++) {
                // 通过lay-id属性过滤表格元素
                var tableLayId = allTableNode[index].getAttribute("lay-id");
                if (tableLayId === tableId) {
                    targetTableNode = allTableNode[index];
                    break;
                }
            }
        }
        if (!targetTableNode) {
            console.log('没有找到ID为：' + tableId + '的表格, 请升级您的layui版本');
            return false;
        }

        // 开始合并单元格操作
        var tBodyNode = targetTableNode.getElementsByClassName("layui-table-body")[0];

        var tdNodes = tBodyNode.getElementsByTagName("td");
        var childFilterArr = [];
        // 获取data-field属性为fieldName的td
        for (var i = 0; i < tdNodes.length; i++) {
            if (tdNodes[i].getAttribute("data-field") === fieldName) {
                childFilterArr.push(tdNodes[i]);
            }
        }

        // 获取td的个数和种类
        var childFilterTextObj = {};
        var childFilterArrLength = childFilterArr.length;
        for (var j = 0; j < childFilterArrLength; j++) {
            var childText = childFilterArr[j].textContent;
            if (childFilterTextObj[childText] === undefined) {
                childFilterTextObj[childText] = 1;
            } else {
                var num = childFilterTextObj[childText];
                childFilterTextObj[childText] = num * 1 + 1;
            }
        }
        // 给获取到的td设置合并单元格属性
        for (var key in childFilterTextObj) {
            var tdNum = childFilterTextObj[key];
            var canRowSpan = true;
            var needChangeBackGroundNodes = [];
            var addEventNode = null;
            for (var h = 0; h < childFilterArrLength; h++) {
                if (childFilterArr[h].textContent === key) {
                    needChangeBackGroundNodes.push(childFilterArr[h]);
                    if (canRowSpan) {
                        childFilterArr[h].setAttribute("rowspan", tdNum);
                        addEventNode = childFilterArr[h];
                        canRowSpan = false;
                    } else {
                        childFilterArr[h].style.display = "none";
                    }
                }
            }

            // 以下为单元格鼠标悬浮样式修改(使用闭包)
            (function (addEventNode, needChangeBackGroundNodes) {
                addEventNode.onmouseover = function () {
                    for (var index = 0, length = needChangeBackGroundNodes.length; index < length; index++) {
                        needChangeBackGroundNodes[index].parentNode.style.background = "#f2f2f2"; // 我这里的单元格鼠标滑过背景色为layui默认，你可以更改为你想要的颜色。
                    }
                };
                addEventNode.onmouseout = function () {
                    for (var index = 0, length = needChangeBackGroundNodes.length; index < length; index++) {
                        needChangeBackGroundNodes[index].parentNode.style.background = "";
                    }
                };
            })(addEventNode, needChangeBackGroundNodes);
        }
    }

    admin.toMsg = function (msgType) {
        if(!msgType){
            return;
        }
        switch (msgType){
            /*case 8:
                top.layui.index.openTabsPage('task/myTaskListTabs.jsp','任务单');
                break;*/
        }
    }



    admin.error = function (e) {
        var cacheData = layui.data(layui.setter.tableName);
        var token = cacheData[layui.setter.request.tokenName];
        if(!token){
            admin.events.logout();
        }else{
        }

    };

    //同步请求 //super_dev_001 2020/2/7
    admin.syncReq = function (url,data,options) {
        if(!options){
            options = {};
        }
        /*if(!options.error){
            options.error=admin.error;
        }*/
        var rtn = null;
        options = $.extend({url:url,type:'post',async:false,data:data,done:function (response) {
            rtn = response;
        }},options);
        view.req(options);
        return rtn;
    };

    //异步请求 //super_dev_001 2020/2/7
    admin.asyncReq = function (url,data,callbackFn) {
        view.req({url:url,type:'post',data:data,done:callbackFn});
    };

    //super_dev_001 2020/3/13
    window.onkeyup=function(ev){
        var key=ev.keyCode||ev.which;
        if(key==27){ //按下Escape
            layer.closeAll(); //疯狂模式，关闭所有层
            if(parent){
                parent.layer.closeAll();
            }
//                layer.closeAll('dialog'); //关闭信息框
//                layer.closeAll('page'); //关闭所有页面层
//                layer.closeAll('iframe'); //关闭所有的iframe层
//                layer.closeAll('loading'); //关闭加载层
//                layer.closeAll('tips'); //关闭所有的tips层
        }
    }

    //super_dev_001 2020/3/13 自定义表单验证
    //value：表单的值、item：表单的DOM对象
    admin.v_email = function(value, item){
        var exp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if(value && !exp.test(value) ){
            return '邮箱格式不正确';
        }
    }

    admin.v_phone = function(value, item){
        var exp = /^1[0-9]{10}$/;
        if(value && !exp.test(value) ){
            return '请输入正确的手机';
        }
    }

    admin.v_url = function(value, item){
        var exp = /(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/;
        if(value && !exp.test(value) ){
            return '链接格式不正确';
        }
    }

    admin.v_number = function(value, item){
        if(value && isNaN(value) ){
            return '只能填写数字';
        }
    }

    admin.v_date = function(value, item){
        var exp = /^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/;
        if(value && !exp.test(value) ){
            return '日期格式不正确';
        }
    }

    admin.v_identity = function(value, item){
        var exp =/(^\d{15}$)|(^\d{17}(x|X|\d)$)/;
        if(value && !exp.test(value) ){
            return '请输入正确的身份证';
        }
    }
    
    admin.guid = function () {
        function S4() {
            return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
        }
        return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
    }

    admin.v_password = function(value, item){
        var exp =/^[0-9a-zA-Z=\\_\\+\\@\\#\\-\\!\\%\\*]{6,}$/;
        if(value && !exp.test(value) ){
            return '请输入至少6位字符';
        }
    }

    /**
     * 用于日期范围的搜索
     * super_dev_001 2020/3/19
     * @param name 搜索的表单值名称，即对应后台Bean的属性
     * @param search_field 搜索字段
     * @param type 日期类型
     */
    admin.renderDateForSearch = function(name,search_field,type,exOptions){
        exOptions = exOptions||{}
        var val = '';
        type = type?type:'date';
        if(search_field && search_field[name+"Start"] && search_field[name+"End"]){
            if(type=='month'){
                val = search_field[name+"Start"].substring(0,7)+" ~ "+search_field[name+"End"].substring(0,7);
            }else if(type=='year'){
                val = search_field[name+"Start"].substring(0,4)+" ~ "+search_field[name+"End"].substring(0,4);
            }else{
                val = search_field[name+"Start"]+" ~ "+search_field[name+"End"];
            }

        }

        var layui_laydate = search_field?top.layui.laydate:layui.laydate;
        var layui$ = search_field?top.layui.$:layui.$;
        layui_laydate.render($.extend({
            elem: '#'+name+'-laydate-range' ,
            type:type,
            trigger: 'click',
            range: '~',
            done: function(value, date, endDate){
                if(!value){
                    layui$(".layui-form [name="+name+"Start]").val(null);
                    layui$(".layui-form [name="+name+"End]").val(null);
                    if(search_field){
                        search_field[name+"Start"] = '';
                        search_field[name+"End"] = '';
                    }
                    return;
                }
                var dateStr1= value.split(" ~ ")[0]
                var dateStr2= value.split(" ~ ")[1]
                if(type=='month'){
                    layui$(".layui-form [name="+name+"Start]").val(dateStr1+'-01');
                    layui$(".layui-form [name="+name+"End]").val(dateStr2+'-01');
                }else if(type=='year'){
                    layui$(".layui-form [name="+name+"Start]").val(dateStr1+'-01-01');
                    layui$(".layui-form [name="+name+"End]").val(dateStr2+'-01-01');
                }else{
                    layui$(".layui-form [name="+name+"Start]").val(dateStr1);
                    layui$(".layui-form [name="+name+"End]").val(dateStr2);
                }
                if(search_field){
                    search_field[name+"Start"] = dateStr1;
                    search_field[name+"End"] = dateStr2;
                }

            }
        },exOptions));
        if(val){
            layui_laydate.render({
                elem: '#'+name+'-laydate-range' ,
                value:val
            });
        }
    }

    //
    /**
     * 日期选择的封装
     * super_dev_001 2020/3/20
     * @param key 日期元素的ID(前缀)
     * @param formData 表单数据
     * @param type
     * @param defaultDate 默认日期
     */
    admin.renderDate = function (key,formData,type,defaultDate,callBackFn,exOptions) {
        exOptions = exOptions?exOptions:{};
        defaultDate = defaultDate?defaultDate:null;
        type = type?type:'date';
        var format = 'yyyy-MM-dd';
        if(type=='year'){
            format = 'yyyy';
        }else if(type=='month'){
            format = 'yyyy-MM';
        }else if(type=='time'){
            format = 'HH:mm:ss';
        }else if(type=='datetime'){
            format = 'yyyy-MM-dd HH:mm:ss';
        }
        format = format?format:'yyyy-MM-dd';
        var date = formData?(formData[key]?formData[key]:defaultDate):defaultDate;
        var instance = null;
        if(date){
            var dateStr = type=='time'?date:layui.util.toDateString(date,format);
            instance = layui.laydate.render($.extend({
                elem: '#'+key+'-laydate',
                trigger: 'click',
                type: type,
                value:dateStr
                ,done: function(value, date, endDate){
                    var formVal = value;
                    if(formVal){
                        if(type=='year'){
                            formVal = value+'-01-01';
                        }else if(type=='month'){
                            formVal = value+'-01';
                        }
                    }
                    $('[name='+key+']').val(formVal)
                    if(callBackFn){
                        callBackFn(value, date, endDate);
                    }
                }
            },exOptions));
        }else{
            instance = layui.laydate.render($.extend({
                elem: '#'+key+'-laydate',
                trigger: 'click',
                type: type
                ,done: function(value, date, endDate){
                    var formVal = value;
                    if(formVal){
                        if(type=='year'){
                            formVal = value+'-01-01';
                        }else if(type=='month'){
                            formVal = value+'-01';
                        }
                    }
                    $('[name='+key+']').val(formVal)
                    if(callBackFn){
                        callBackFn(value, date, endDate);
                    }
                }
            },exOptions));
        }
        return instance;
    }

    //super_dev_007 2021/2/12
    admin.regionSel = function (xmSelect,elId,provinceId,cityId,areaId) {
        function setRegion(node) {
            if(!node){
                $("[name=provinceId]").val("");
                $("[name=provinceName]").val("");
                $("[name=areaId]").val("");
                $("[name=areaName]").val("");
                $("[name=cityId]").val("");
                $("[name=cityName]").val("");
                return;
            }
            var type = node.type;
            if(type==3){
                $("[name=areaId]").val(node.id);
                $("[name=areaName]").val(node.name);
                var pnode = node.parent;
                $("[name=cityId]").val(pnode.id);
                $("[name=cityName]").val(pnode.name);
                var ppnode = pnode.parent;
                $("[name=provinceId]").val(ppnode.id);
                $("[name=provinceName]").val(ppnode.name);
            }else if(type==2){
                $("[name=cityId]").val(node.id);
                $("[name=cityName]").val(node.name);
                var pnode = node.parent;
                $("[name=provinceId]").val(pnode.id);
                $("[name=provinceName]").val(pnode.name);

                $("[name=areaId]").val("");
                $("[name=areaName]").val("");
            }else if(type==1){
                $("[name=provinceId]").val(node.id);
                $("[name=provinceName]").val(node.name);

                $("[name=areaId]").val("");
                $("[name=areaName]").val("");
                $("[name=cityId]").val("");
                $("[name=cityName]").val("");
            }
        }
        var regionData = [];
        var url = ctx+'/base/region/queryAll';
        var rtnRegion=admin.syncReq(url,{parentId:0});
        regionData = rtnRegion.data;
        var provinceXmSelect = xmSelect.render({
            el: '#'+elId,
            autoRow: true,
            filterable: true,
            model: {
                label: {
                    block: {
                        //自定义渲染label, 默认渲染name, 回调参数(item, sels)
                        template: function (item, sels) {
                            var rtnLabel = '';
                            var parent = item.parent;
                            if(parent){
                                if(parent.parent){
                                    rtnLabel=parent.parent.name+'/'
                                }
                                rtnLabel+=parent.name+'/';
                            }
                            rtnLabel+=item.name;
                            return rtnLabel;
                        },
                    },
                },
                //展示类型, 下拉框形式: absolute, 直接显示模式: relative
                type: 'absolute',
            },
            tree: {
                //是否显示树状结构
                show: true,
                //是否展示三角图标
                showFolderIcon: true,
                //是否显示虚线
                showLine: false,
                //间距
                indent: 20,
                //默认展开节点的数组, 为 true 时, 展开所有节点
                expandedKeys: [],
                //是否严格遵守父子模式
                strict: false,
                lazy: true,
                load:function (item,cb) {
                    if(item.type==3){
                        cb([])
                    }else{
                        if(!item.children || item.children.length==0){
                            var _rtn=admin.syncReq(url,{parentId:item.id});
                            if(_rtn.data && _rtn.data.length>0){
                                var children = _rtn.data;
                                $.each(children,function (index,_item) {
                                    if(_item.type==3){
                                        _item.children = null;
                                    }
                                    var _parent = {name:item.name,id:item.id,type:item.type}
                                    if(item.parent){
                                        _parent = $.extend(_parent,{parent:item.parent});
                                    }
                                    _item = $.extend(_item,{ parent:_parent });
                                })
                                cb(children);
                                // item.children = children;
                                // provinceXmSelect.reset();
                            }
                        }else{
                            cb([])
                        }
                    }

                }
            },
            height: '200px',
            radio:true,
//            clickClose:true,
            data(){
                return regionData;
            },
            on:function (data) {
                var arr = data.arr;
                if(arr && arr.length>0){
                    var node = arr[0];
                    if(node.type==3){
                        provinceXmSelect.closed();
                    }
                    setRegion(node)
                }else{
                    setRegion(null);
                }
            }
        });

        var selNode = {};
        var cityNode = null;
        var provinceNode = null;
        if(provinceId){
            $.each(regionData,function (index,item) {
                if(item.id==provinceId){
                    provinceNode = item;
                    return false;
                }
            })
            var _rtn=admin.syncReq(url,{parentId:provinceId});
            var cityList = _rtn.data;
            $.each(cityList,function (index,item) {
                item.children = null;
                item = $.extend(item,{parent:{name:provinceNode.name,id:provinceNode.id,type:provinceNode.type}})
            })
            selNode.children = cityList;
        }

        if(cityId){
            var _rtn=admin.syncReq(url,{parentId:cityId});
            var areaList = _rtn.data;
            if(selNode.children){
                $.each(selNode.children,function (index,item) {
                    if(item.id==cityId){
                        cityNode = item;
                        item.children = areaList;
                        return false;
                    }
                })
            }
            $.each(areaList,function (index,item) {
                item.children=null;
                var parent1 = {name:provinceNode.name,id:provinceNode.id,type:provinceNode.type}
                var parent2 = {parent:{name:cityNode.name,id:cityNode.id,type:cityNode.type,parent:parent1}}
                if(cityNode){
                    item = $.extend(item,parent2);
                }
            })

        }

        if(provinceId){
            $.each(regionData,function (index,item) {
                if(item.id==provinceId){
                    provinceNode = item;
                    item.children = selNode.children;
                    return false;
                }
            })
        }
        provinceXmSelect.reset();

        if(areaId){
            provinceXmSelect.setValue([areaId])
        }else if(cityId){
            provinceXmSelect.setValue([cityId])
        }else if(provinceId){
            provinceXmSelect.setValue([provinceId])
        }
        return provinceXmSelect;
    }

    //弃用...
    admin.xmSelectRegion =function (xmSelect,el,onFn,provinceId,cityId,areaId) {
        var regionData = [];
        var url = ctx+'/base/region/queryAll';
        var rtnRegion=admin.syncReq(url,{parentId:0});
        regionData = rtnRegion.data;
        var provinceXmSelect = xmSelect.render({
            el: '#'+el,
            autoRow: true,
            filterable: true,
            model: {
                label: {
                    block: {
                        //自定义渲染label, 默认渲染name, 回调参数(item, sels)
                        template: function (item, sels) {
                            var rtnLabel = '';
                            var parent = item.parent;
                            if(parent){
                                if(parent.parent){
                                    rtnLabel=parent.parent.name+'/'
                                }
                                rtnLabel+=parent.name+'/';
                            }
                            rtnLabel+=item.name;
                            return rtnLabel;
                        },
                    },
                },
                //展示类型, 下拉框形式: absolute, 直接显示模式: relative
                type: 'absolute',
            },
            tree: {
                //是否显示树状结构
                show: true,
                //是否展示三角图标
                showFolderIcon: true,
                //是否显示虚线
                showLine: false,
                //间距
                indent: 20,
                //默认展开节点的数组, 为 true 时, 展开所有节点
                expandedKeys: [],
                //是否严格遵守父子模式
                strict: false,
                lazy: true,
                load:function (item,cb) {
                    if(item.type==3){
                        cb([])
                    }else{
                        if(!item.children || item.children.length==0){
                            var _rtn=admin.syncReq(url,{parentId:item.id});
                            if(_rtn.data && _rtn.data.length>0){
                                var children = _rtn.data;
                                $.each(children,function (index,_item) {
                                    if(_item.type==3){
                                        _item.children = null;
                                    }
                                    var _parent = {name:item.name,id:item.id,type:item.type}
                                    if(item.parent){
                                        _parent = $.extend(_parent,{parent:item.parent});
                                    }
                                    _item = $.extend(_item,{ parent:_parent });
                                })
                                cb(children);
                                // item.children = children;
                                // provinceXmSelect.reset();
                            }
                        }else{
                            cb([])
                        }
                    }

                }
            },
            height: '200px',
            radio:true,
//            clickClose:true,
            data(){
                return regionData;
            },
            on:function (data) {
                var arr = data.arr;
                if(arr && arr.length>0){
                    var node = arr[0];
                    if(node.type==3){
                        provinceXmSelect.closed();
                    }
                    if(onFn){
                        onFn(node);
                    }
                }else{
                    onFn(null);
                }
            }
        });

        var selNode = {};
        var cityNode = null;
        var provinceNode = null;
        if(provinceId){
            $.each(regionData,function (index,item) {
                if(item.id==provinceId){
                    provinceNode = item;
                    return false;
                }
            })
            var _rtn=admin.syncReq(url,{parentId:provinceId});
            var cityList = _rtn.data;
            $.each(cityList,function (index,item) {
                item.children = null;
                item = $.extend(item,{parent:{name:provinceNode.name,id:provinceNode.id,type:provinceNode.type}})
            })
            selNode.children = cityList;
        }

        if(cityId){
            var _rtn=admin.syncReq(url,{parentId:cityId});
            var areaList = _rtn.data;
            if(selNode.children){
                $.each(selNode.children,function (index,item) {
                    if(item.id==cityId){
                        cityNode = item;
                        item.children = areaList;
                        return false;
                    }
                })
            }
            $.each(areaList,function (index,item) {
                item.children=null;
                var parent1 = {name:provinceNode.name,id:provinceNode.id,type:provinceNode.type}
                var parent2 = {parent:{name:cityNode.name,id:cityNode.id,type:cityNode.type,parent:parent1}}
                if(cityNode){
                    item = $.extend(item,parent2);
                }
            })

        }

        if(provinceId){
            $.each(regionData,function (index,item) {
                if(item.id==provinceId){
                    provinceNode = item;
                    item.children = selNode.children;
                    return false;
                }
            })
        }
        provinceXmSelect.reset();

        if(areaId){
            provinceXmSelect.setValue([areaId])
        }else if(cityId){
            provinceXmSelect.setValue([cityId])
        }else if(provinceId){
            provinceXmSelect.setValue([provinceId])
        }
        return provinceXmSelect;
    }

    //cjq 2022/4/11
    admin.renderXmSelV2 = function (xmSelect,params){
        var where = params.where||{};
        var url = params.url;
        var dataArr = [];
        var data = params.data || [];
        if(url){
            var dataRtn = admin.syncReq(url,where);
            if(dataRtn.code==0){
                dataArr = dataRtn.data;
            }
        }else if(data && data.length>0){
            dataArr = data;
        }

        var initValue = params.value || '';
        var initValueArr = params.values || [];
        if(initValueArr.length==0){
            if(initValue){
                initValueArr.push(initValue)
            }
        }

        var elId = params.elId || '';
        var prop = (params.options && params.options.prop) || {name:'name',value:'id'};
        var options = {
            el: '#'+elId+'Sel',
            prop: prop,
            data: dataArr,
            initValue:initValueArr,
            radio:true,
            clickClose:true,
            on:function (data) {
                setTimeout(function () {
                    //arr:  当前多选已选中的数据
                    var arr = data.arr;
                    var selValArr = [];
                    var selNameArr = [];
                    for(var i=0;i<arr.length;i++){
                        var node = arr[i];
                        selValArr.push(node[prop.value])
                        selNameArr.push(node[prop.name]);
                    }
                    if(selValArr.length>0){
                        $("[name="+elId+"Id]").val(selValArr.join(","));
                        $("[name="+elId+"Name]").val(selNameArr.join(","));
                    }else{
                        $("[name="+elId+"Id]").val("");
                        $("[name="+elId+"Name]").val("");
                    }
                },100)
            }
        };
        options = $.extend(options,params.options);
        var xmSel = xmSelect.render(options);
    }

    //super_dev_007 2021/2/12
    admin.renderXmSel = function (xmSelect,elId,url,valArr,data,props,mult) {
        var dataArr = [];
        if(url){
            var dataRtn = admin.syncReq(url,{});
            if(dataRtn.code==0){
                dataArr = dataRtn.data;
            }
        }else if(data && data.length>0){
            dataArr = data;
        }
        if(!props){
            props = {name:'name',value:'id'};
        }
        if(!valArr || valArr.length==0){
            valArr = [];
        }
        valArr = valArr.filter(function (v) {
            if(v==null){
                return false;
            }else if(v==undefined){
                return false;
            }
            return true;
        });

        mult = mult==false?mult:true;
        var xmSel = xmSelect.render({
            el: '#'+elId+'Sel',
            prop:props,
            data: dataArr,
            initValue:valArr,
            radio:mult,
            clickClose:mult,
            on:function (data) {
                setTimeout(function () {
                    var valueStr = xmSel.getValue("valueStr");
                    var nameStr = xmSel.getValue("nameStr");
                    if(valueStr){
                        $("[name="+elId+"Id]").val(valueStr);
                    }else{
                        $("[name="+elId+"Id]").val("");
                    }
                    if(nameStr){
                        $("[name="+elId+"Name]").val(nameStr);
                    }else{
                        $("[name="+elId+"Name]").val("");
                    }
                },100)

            }
        });
    }
    
    //super_dev_007 2021/2/12
    admin.picUpload = function (upload,elId,initUrl) {
        if(initUrl){
            $('#'+elId+'-upload-img').attr('src', initUrl);
        }
        var uploadInst = upload.render({
            elem: '#'+elId+'-upload'
            ,field:'picFile'
            ,accept:"images"
            ,acceptMime:"image/*"
            ,auto:false
            ,data: {fileName:''} //请求上传的额外参数
            ,url: ctx+'/upload/img-upload'
            ,choose:function (obj){
                obj.preview(function(index, file, result){
                    var s = file.size/1024/1024;
                    if(s>0){
                        admin.photoCompress(file,{ scale: 1.5 },
                            function(base64Codes){
                                var bl = admin.convertBase64UrlToBlob(base64Codes)
                                var fileName = file.name;
                                $('#'+elId+'-upload-img').attr('src', base64Codes); //图片链接（base64）
                                obj.resetFile(index, bl, fileName);
                                var formData = new FormData();
                                formData.append("picFile", bl, fileName);
                                var options = {processData : false,contentType : false};
                                var rs = admin.syncReq(ctx+'/upload/img-upload',formData,options)
                            });
                    }else{
                        var formData = new FormData();
                        var fileName = file.name;
                        formData.append("picFile", file, fileName);
                        var options = {processData : false,contentType : false};
                        var rs = admin.syncReq(ctx+'/upload/img-upload',formData,options)
                    }
                });
            }
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
            }
            ,done: function(res){
                //如果上传失败
                if(res.success !=true){
                    return layer.msg('上传失败');
                }
                //上传成功
                $('#'+elId+'-upload-img').attr('src', res.url);
                $("[name="+elId+"]").val(res.url)
            }
            ,error: function(){
            }
        });
    }

    /*
        三个参数
        file：一个是文件(类型是图片格式)，
        w：一个是文件压缩的后宽度，宽度越小，字节越小
        objDiv：一个是容器或者回调函数
        photoCompress()
         */
    admin.photoCompress = function (file,w,objDiv){
        var ready=new FileReader();
        /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
        ready.readAsDataURL(file);
        ready.onload=function(){
            var re=this.result;
            admin.canvasDataURL(re,w,objDiv)
        }
    }
    admin.canvasDataURL = function (path, obj, callback){
        var img = new Image();
        img.src = path;
        img.onload = function(){
            var that = this;
            // 默认按比例压缩
            var w = that.width,
                h = that.height,
                scale = obj.scale || w / h;
            w = obj.width || (w / scale);
            h = obj.height || (h / scale);
            var quality = 0.7;  // 默认图片质量为0.7
            //生成canvas
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');
            // 创建属性节点
            var anw = document.createAttribute("width");
            anw.nodeValue = w;
            var anh = document.createAttribute("height");
            anh.nodeValue = h;
            canvas.setAttributeNode(anw);
            canvas.setAttributeNode(anh);
            ctx.drawImage(that, 0, 0, w, h);
            // 图像质量
            if(obj.quality && obj.quality <= 1 && obj.quality > 0){
                quality = obj.quality;
            }
            // quality值越小，所绘制出的图像越模糊
            var base64 = canvas.toDataURL('image/jpeg', quality);
            // 回调函数返回base64的值
            callback(base64);
        }
    }

    admin.convertBase64UrlToBlob = function (urlData){
        var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {type:mime});
    }

    //super_dev_001 2020/3/30 支持点击行的任意单元格即选中该行，其他行取消选择
    admin.tableRowCheckToggle = function () {
        $('body').on('click', '.layui-table-body tr', function(e){
            $('.layui-form-checkbox', this).click();
            $('.layui-form-checkbox.layui-form-checked', this.parent).click();
            $('.layui-form-checkbox', this).click();

        })
        $('body').on('click', '.layui-form-checkbox', function(e){
            e.stopPropagation();
        })
    }

    //计算两个时间差
    //dateStart、dateEnd Date 格式
    //type=d 天数 M 月份 y 年数 h 小时数  m 分钟 s 秒数
    admin.dateDiff = function (dateStart,dateEnd,type) {
        var cnt = 0;
        //先做 M 月份
        if(type=='M'){
            dateStart.setTime(new Date(dateStart.getFullYear(), dateStart.getMonth() , 1));
            dateEnd.setTime(new Date(dateEnd.getFullYear(),dateEnd.getMonth() , 1))
            var date2Mon;
            if(dateEnd>=dateStart){
                date2Mon=0;
            }else{
                date2Mon=-1;
            }
            cnt = (dateEnd.getYear()-dateStart.getYear())*12+dateEnd.getMonth()-dateStart.getMonth()+date2Mon+1;
        }

        return cnt
    }

    //super_dev_001 2019/7/12
    //date之后n个月，负数为前n个月
    //参数为空，默认返回当前时间
    admin.addMonths = function (_date,_interval){
        if(!_date){
            return new Date();
        }
        if(!_interval){
            _interval = 0;
        }
        var month = _date.getMonth() + _interval;
        var rtn = new Date(_date.getFullYear(),month,1);
        return rtn;
    }

    admin.addDays = function (_date,_interval) {
        if(!_date){
            return new Date();
        }
        if(!_interval){
            _interval = 0;
        }
        var result =  _date.getTime()+(_interval*1000*60*60*24);
        return (new Date(result));
    }

    //super_dev_001 2020/6/11 本周第一天
    admin.thisWeekStart = function () {
        var now = new Date(); //当前日期
        var nowDayOfWeek = now.getDay(); //今天本周的第几天
        var nowDay = now.getDate(); //当前日
        var nowMonth = now.getMonth(); //当前月
        var nowYear = now.getFullYear(); //当前年
        var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
        return weekStartDate;
    }
    admin.thisMonthStart = function () {
        var now = new Date(); //当前日期
        var nowMonth = now.getMonth(); //当前月
        var nowYear = now.getFullYear(); //当前年
        var monthStartDate = new Date(nowYear, nowMonth, 1);
        return monthStartDate;
    }
    admin.thisYearStart = function () {
        var now = new Date(); //当前日期
        var nowYear = now.getFullYear(); //当前年
        var yearStartDate = new Date(nowYear, 0, 1);
        return yearStartDate
    }

    admin.toLoginPage = function () {
        var logonUrl = ctx+layui.setter.loginPageUrl
        try{
            parent.location.href = logonUrl;
        }catch(e){
            location.href = logonUrl;
        }
    }

    admin.tableDone = function (res){
        if(res.code==layui.setter.response.statusCode.logout){
            layer.alert('登录已过期，请重新登录',function (){
                admin.toLoginPage();
            })
        }
    }

  //退出
  admin.events.logout = function(){
    //执行退出接口
    admin.req({
      // url: layui.setter.base + 'json/user/logout.js'
        url:  ctx+layui.setter.logoutActionUrl
      ,type: 'get'
      ,data: {}
      ,done: function(res){ //这里要说明一下：done 是只有 response 的 code 正常才会执行。而 succese 则是只要 http 为 200 就会执行
        
        //清空本地记录的 token，并跳转到登入页
            admin.exit(admin.toLoginPage);
        /*admin.exit(function(){
            admin.exit( admin.toLoginPage );
        });*/
      }
    });
  };

  //对外暴露的接口
  exports('common', {});
});